<div class="content-wrapper">
    <!-- Content Header (Page header) -->

    <style>
        .productGoodsList td div{
            width: 100%;
            min-height: 20px;
        }
    </style>
    
    <section class="content">
        
    	<div class="box box-primary">
            <div class="box-header with-border">
                <h3 class="box-title">订单<?=$order_id ? '#'.$order_id : ''?> <small>生产订单</small></h3>
            </div>
            <div class="alert">
                <button class="btn btn-primary addRow">添加产品</button>
                <button class="btn btn-primary exportExcel">导出Excel</button>
            </div>
            <div style="position:absolute; right: 10px; top: 45px;">
                <form class="form-inline">
                    <div class="form-group">
                        <label>尺寸</label>
                        <select class="form-control lengthUnit">
                            <option value="mm">厘米(mm)</option>
                            <option value="inch">英寸(inch)</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>重量</label>
                        <select class="form-control weightUnit">
                            <option value="kg">千克(kg)</option>
                            <option value="lb">英镑(lb)</option>
                        </select>
                    </div>
                </form>
            </div>

            <div class="alert alert-info productsList">
                
            </div>
            
            <table class="table table table-striped table-hover table-bordered table-condensed productGoodsList">
                <thead>
                    <tr>
                        <th>型号</th>
                        <th>产品名称</th>
                        <th>生产数量</th>
                        <th>单价</th>
                        <th>总价</th>
                        <th>彩盒长mm</th>
                        <th>彩盒宽mm</th>
                        <th>彩盒高mm</th>
                        <th>外箱长mm</th>
                        <th>外箱宽mm</th>
                        <th>外箱高mm</th>
                        <th>单件重量KG</th>
                        <th>每箱数量</th>
                        <th>每箱重量KG</th>
                        <th>总重量KG</th>
                        
                        <th>箱数</th>
                        <th>说明</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    
                </tbody>
            </table>
            
            <div class="text-center">
                <div class="btn btn-success save">保存</div>
            </div>
            <br />

            
        </div>
    </section>

    <script>
        order_id = <?=$order_id?>;

        $(function(){
            let baseUnit = {
                'kg': 'kg',
                'mm': 'mm',
                'm³': 'm³'
            }
            $('.lengthUnit').val(baseUnit['mm']);
            $('.weightUnit').val(baseUnit['kg']);
            $('.lengthUnit').on('change', function(e) {
                baseUnit['mm'] = $(this).val();
                updateLengthUnit();
            })
            $('.weightUnit').on('change', function(e) {
                baseUnit['kg'] = $(this).val();
                updateWeightUnit();
            })

            var tableConfig = [
                {
                    prop: 'productModel',
                    label: '型号',
                    col: 1
                },
                {
                    prop: 'productName',
                    label: '产品名称',
                    col:2
                },
                {
                    prop: 'quantity',
                    label: '生产数量',
                    col:3
                },
                {
                    prop: 'price',
                    label: '单价',
                    col:4
                },
                {
                    prop: 'totalPrice',
                    label: '总价',
                    col:5
                },
                {
                    prop: 'boxLength',
                    label: '彩盒长',
                    unit: 'mm',
                    col:6
                },
                {
                    prop: 'boxWidth',
                    label: '彩盒宽',
                    unit: 'mm',
                    col:7
                },
                {
                    prop: 'boxHeight',
                    label: '彩盒高',
                    unit: 'mm',
                    col:8
                },
                {
                    prop: 'packageLength',
                    label: '外箱长',
                    unit: 'mm',
                    col:9
                },
                {
                    prop: 'packageWidth',
                    label: '外箱宽',
                    unit: 'mm',
                    col:10
                },
                {
                    prop: 'packageHeight',
                    label: '外箱高',
                    unit: 'mm',
                    col:11
                },

                {
                    prop: 'weight',
                    label: '单件重量',
                    unit: 'kg',
                    col:12
                },
                {
                    prop: 'quantityPerPack',
                    label: '每箱数量',
                    col:13
                },

                {
                    prop: 'weightPerPack',
                    label: '每箱重量',
                    unit: 'kg',
                    col:14
                },

                {
                    prop: 'totalWeight',
                    label: '总重量',
                    unit: 'kg',
                    col:15
                },
                
                {
                    prop: 'packagesCount',
                    label: '箱数',
                    col:16
                },
                {
                    prop: 'remark',
                    label: '说明',
                    col:17
                },
            ];

            var COL = {
                PCS: 7,
                PCS_WEIGHT: 9,
                BOX_TOTAL: 8,
                PCS_WEIGHT_TOTAL : 10,
                WEIGHT_TOTAL: 11,
                BOX_LENGTH: 14,
                BOX_WIDTH: 15,
                BOX_HEIGHT: 16,
                BOX_BULK: 17
            };


            
            function runCallback(dom, flag){
                var funs = flag.split('|');
                var tr = dom.closest('tr');
                
                var getV = function(num){
                    return tr.find('td').eq(num - 1).find('div').html();
                }
                var getT = function(num) {
                    return tr.find('td').eq(num-1).find('div');
                }
                if(funs.includes('weight')) {
                    getT(COL.PCS_WEIGHT_TOTAL).html((getV(COL.PCS) * getV(COL.PCS_WEIGHT)).toFixed(2));
                    getT(COL.WEIGHT_TOTAL).html((getV(COL.PCS) * getV(COL.PCS_WEIGHT) * getV(COL.BOX_TOTAL)).toFixed(2));
                }
                if(funs.includes('bulk')){
                    getT(COL.BOX_BULK).html((getV(COL.BOX_LENGTH) * getV(COL.BOX_WIDTH) * getV(COL.BOX_HEIGHT) * getV(8) / 1000000).toFixed(2))
                }
            }
            function addRow(row, readOnly){
                var tr = $('<tr/>');
                $(tableConfig).each(function(index, td){
                    $(`<td><div data-action="edit" data-change="${td.change}" data-unit="${td.unit || ''}" prop="${td.prop}">${row[td.prop] || ''}</div></td>`).appendTo(tr);
                })
                if(!readOnly) {
                    $(`<td>
                                <div data-action="delete">
                                    <a href="javascript:void(0)" class="btn btn-sm btn-danger">删除</a>
                                </div>
                            </td> `).appendTo(tr);
                }
                updateLengthUnit(tr, 'mm');
                updateWeightUnit(tr, 'kg');
                tr.appendTo($('.productGoodsList tbody'));
            }

            $('.addRow').on('click', function(){
                addRow({}, false)
            })

            $('.exportExcel').on('click', function(){
                $.ajax({
                    url: '/orders/exportProducts/' + order_id,
                    type: 'post',
                    cache: false,
                    xhr: function(){
                        var xhr = new XMLHttpRequest()
                        xhr.responseType = 'blob'
                        return xhr
                    },
                    data: {
                        id: order_id,
                        columns: tableConfig,
                        source: 'getProductOrder'
                    },
                    success: function(res){
                        console.log(res);
                        var reader = new FileReader();
                        reader.readAsDataURL(res); 
                        reader.onload = function(e) {
                            var a = document.createElement('a');
                           a.download = `生产订单_${order_id}.xlsx`;
                           a.href = e.target.result;
                           $("body").append(a);    // 修复firefox中无法触发click
                           a.click();
                           $(a).remove();
                        }

                        
                    }
                })
            })


            $('.productGoodsList tbody').on('click', '[data-action]', function(){
                var action = $(this).attr('data-action');
                if(action == 'edit') {
                    let dom = $(this);
                    $(this).attr('contenteditable', true).focus();
                    dom.on('blur',function(){
                        $(this).removeAttr('contenteditable');
                        if($(this).data('callback')) {
                            runCallback(dom, $(this).data('callback'));
                        }
                    })
                    dom.on('keydown', function(e){
                        if(e.which == 13 || e.which == 27) {
                            dom.trigger('blur');
                            reCalc(dom);
                            return false;
                        }
                        
                    })
                }
                if(action == 'delete') {
                    let dom = $(this);
                    dom.closest('tr').remove();
                }
                    
            })

            $('.save').on('click', function(){
                var products = [];
                $('.productGoodsList tbody').find('tr').each(function(){
                    let row = $(this).data('product') || {};
                    $(this).find('[prop]').each(function(){
                        let prop = $(this).attr('prop');
                        row[prop] = $(this).text();
                    })
                    products.push(row);
                })
                var order = $('.productGoodsList').data('order') || {};
                order['products'] = products;
                $.post('/orders/saveProductOrder', {order: order}).then(function(res) {
                    window.location.href="/orders/createProduct/" + res.order_id
                }, function(err){
                    alert(err.statusText)
                });
            })

            function loadOrder(){
                $.get('/orders/getProductOrder', {id: order_id}).then(function(res){
                    $('.productGoodsList').data('order', res);
                    $.each(res.products, function(index, pro) {
                        addRow(pro, false)    
                    })
                }, function(err){
                    alert(err.statusText)
                })
            }

            function loadProducts(){
                $.get('/orders/getProducts', {id: order_id}).then(function(res){
                    $(res).each(function(index, item) {
                        var pro = $('<div class="badge mr-1"/>').html(item.productModel + '-' + item.productName).data('product', item);
                        $('.productsList').append(pro);
                        pro.on('click', function(){
                            addRow($(pro).data('product'), false);
                        })

                    })
                    
                    console.log(res)
                }, function(err){
                    alert(err.statusText)
                })
            }

            function reCalc(dom){

            }

            function renderCodeHeader(){
                var thead = $('thead tr');
                thead.empty();
                let config = tableConfig;
                $(config).each(function(index, item){
                    $('<th />').html(item.label + getHeaderUnit(item.unit || '')).appendTo(thead);
                })
                $('<th />').html('操作').appendTo(thead);
            }

            function getHeaderUnit(unit){
                return unit ? `(${baseUnit[unit]})` : ''
            }

            function updateWeightUnit(dom, initUnit){
                renderCodeHeader();
                let unitValue = 2.2046226;
                if(!dom) dom = $('.productGoodsList');
                dom.find('[data-unit=kg]').each(function(){
                    let v = $(this).text(), _v;
                    if(v && initUnit != baseUnit['kg']) {
                        switch(baseUnit['kg']){
                            case 'kg':
                                _v = +v / unitValue
                                break;
                            case 'lb':
                                _v = +v * unitValue
                                break;  
                        }
                        $(this).text(_v.toFixed(2));
                    }
                })

            }
            function updateLengthUnit(dom, initUnit){
                renderCodeHeader();
                let unitValue = 0.3937008;
                if(!dom) dom = $('.productGoodsList');
                dom.find('[data-unit=mm]').each(function(){
                    let v = $(this).text(), _v;
                    if(v && initUnit != baseUnit['mm']) {
                        switch(baseUnit['mm']){
                            case 'mm':
                                _v = +v / unitValue
                                break;
                            case 'inch':
                                _v = +v * unitValue
                                break;
                        }

                        $(this).text(_v.toFixed(2));
                    }
                })
            }

            function unitVal(val, conf) {
                return val
            }

            if(order_id){
                loadOrder();
            }
            loadProducts();
        })
    </script>

    
</div>